package jwt

import (
	"errors"
	"github.com/fatih/structs"
	"github.com/golang-jwt/jwt/v4"
	"github.com/vueadmin/global"
	"time"
)

type Jwt struct {
	SigningKey []byte
	Exp        int64
	Iss        string
	Aud        string
}

var (
	TokenExpired     = errors.New("Token is expired")
	TokenNotValidYet = errors.New("Token not active yet")
	TokenMalformed   = errors.New("That's not even a token")
	TokenInvalid     = errors.New("Couldn't handle this token:")
)

func NewJwt(app string) *Jwt {
	if app == "admin" {
		jwtconfig := global.CONF.Adminjwt
		return &Jwt{
			SigningKey: []byte(jwtconfig.SigningKey),
			Exp:        jwtconfig.ExpiresTime,
			Iss:        jwtconfig.Issuer,
			Aud:        jwtconfig.Aud,
		}
	} else {
		jwtconfig := global.CONF.Apijwt
		return &Jwt{
			SigningKey: []byte(jwtconfig.SigningKey),
			Exp:        jwtconfig.ExpiresTime,
			Iss:        jwtconfig.Issuer,
			Aud:        jwtconfig.Aud,
		}
	}
}

// 创建token
func (p Jwt) CreateToken(data interface{}) (string, error) {
	baseClaims := jwt.MapClaims{
		"exp": time.Now().Unix() + p.Exp,
		"iat": time.Now().Unix(),
		"iss": p.Iss,
		"aud": p.Aud,
	}
	info := structs.Map(data)
	for key, val := range info {
		baseClaims[key] = val
	}
	claims := jwt.NewWithClaims(jwt.SigningMethodHS256, baseClaims)
	signingString, err := claims.SignedString(p.SigningKey)
	if err != nil {
		global.LOG.Error("token创建失败", err)
		return "", err
	}
	return signingString, nil
}

// 解析token
func (p Jwt) ParseToken(tokenstr string) (jwt.Claims, error) {
	token, err := jwt.ParseWithClaims(tokenstr, jwt.MapClaims{}, func(token *jwt.Token) (i interface{}, e error) {
		return p.SigningKey, nil
	})

	if err != nil {
		if ve, ok := err.(*jwt.ValidationError); ok {
			if ve.Errors&jwt.ValidationErrorMalformed != 0 {
				return nil, TokenMalformed
			} else if ve.Errors&jwt.ValidationErrorExpired != 0 {
				return nil, TokenExpired
			} else if ve.Errors&jwt.ValidationErrorNotValidYet != 0 {
				return nil, TokenNotValidYet
			} else {
				return nil, TokenInvalid
			}
		}
	}
	if token != nil && token.Valid {
		return token.Claims, nil
	} else {
		return nil, TokenInvalid
	}
}
